// 博客管理系统 - 连接真实数据库
class BlogManager {
    constructor() {
        this.baseUrl = 'http://localhost:3000';
        this.currentTab = 'all';
        this.currentPage = 1;
        this.pageSize = 10;
        this.articles = [];
        this.init();
    }

    async init() {
        await this.loadArticles();
        this.setupEventListeners();
        console.log('博客管理系统已初始化');
    }

    // 设置事件监听器
    setupEventListeners() {
        // 搜索功能
        const searchInput = document.createElement('input');
        searchInput.type = 'text';
        searchInput.placeholder = '搜索文章标题或内容...';
        searchInput.style.cssText = `
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 300px;
            margin-left: 20px;
        `;
        searchInput.addEventListener('input', (e) => {
            this.searchArticles(e.target.value);
        });

        // 将搜索框添加到页面
        const header = document.querySelector('.blog-header');
        if (header) {
            header.appendChild(searchInput);
        }
    }

    // 加载文章列表
    async loadArticles(status = null) {
        try {
            let url = `${this.baseUrl}/api/articles?page=${this.currentPage}&limit=${this.pageSize}`;
            if (status) {
                url += `&status=${status}`;
            }

            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            if (result.success) {
                this.articles = result.data.articles || [];
                this.renderArticles();
                this.renderPagination(result.data.total || 0);
            } else {
                this.showNotification('加载文章失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('加载文章失败:', error);
            this.showNotification('网络错误，请检查后端服务是否启动', 'error');
            // 显示空状态
            this.renderEmptyState();
        }
    }

    // 渲染文章列表
    renderArticles() {
        const container = document.querySelector(`#${this.currentTab}-articles .article-list`);
        if (!container) return;

        if (this.articles.length === 0) {
            container.innerHTML = `
                <div style="text-align: center; padding: 60px 20px; color: #666;">
                    <i class="fas fa-file-alt" style="font-size: 48px; margin-bottom: 20px;"></i>
                    <h3>暂无文章</h3>
                    <p>点击"创作"按钮开始撰写您的博客文章</p>
                </div>
            `;
            return;
        }

        container.innerHTML = this.articles.map(article => this.createArticleCard(article)).join('');
    }

    // 创建文章卡片
    createArticleCard(article) {
        const statusText = {
            'draft': '草稿',
            'published': '已发布',
            'deleted': '已删除'
        }[article.status] || article.status;

        const statusClass = {
            'draft': 'draft',
            'published': 'published',
            'deleted': 'deleted'
        }[article.status] || '';

        return `
            <div class="article-item ${statusClass}">
                <h3>${this.escapeHtml(article.title)}</h3>
                <p class="article-meta">
                    ${article.category || '未分类'} | 
                    ${this.formatTime(article.createdAt || article.created_at)} | 
                    ${statusText}
                </p>
                <p class="article-excerpt">
                    ${this.escapeHtml(this.getExcerpt(article.content))}
                </p>
                <div class="article-actions">
                    ${article.status !== 'deleted' ? `
                        <button onclick="blogManager.editArticle(${article.id})">编辑</button>
                        <button onclick="blogManager.deleteArticle(${article.id})">删除</button>
                    ` : `
                        <button onclick="blogManager.restoreArticle(${article.id})">恢复</button>
                        <button onclick="blogManager.permanentDelete(${article.id})">永久删除</button>
                    `}
                    ${article.status === 'draft' ? `
                        <button onclick="blogManager.publishArticle(${article.id})">发布</button>
                    ` : ''}
                </div>
            </div>
        `;
    }

    // 渲染分页
    renderPagination(totalItems) {
        const totalPages = Math.ceil(totalItems / this.pageSize);
        const paginationContainer = document.createElement('div');
        paginationContainer.className = 'pagination';
        
        if (totalPages <= 1) {
            paginationContainer.innerHTML = '';
            return;
        }

        let paginationHtml = '';
        
        // 上一页
        if (this.currentPage > 1) {
            paginationHtml += `<button class="page-btn" onclick="blogManager.goToPage(${this.currentPage - 1})">上一页</button>`;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === this.currentPage) {
                paginationHtml += `<button class="page-btn active">${i}</button>`;
            } else if (i >= this.currentPage - 2 && i <= this.currentPage + 2) {
                paginationHtml += `<button class="page-btn" onclick="blogManager.goToPage(${i})">${i}</button>`;
            }
        }

        // 下一页
        if (this.currentPage < totalPages) {
            paginationHtml += `<button class="page-btn" onclick="blogManager.goToPage(${this.currentPage + 1})">下一页</button>`;
        }

        paginationContainer.innerHTML = paginationHtml;
        
        // 添加到页面
        const container = document.querySelector(`#${this.currentTab}-articles`);
        if (container) {
            const existingPagination = container.querySelector('.pagination');
            if (existingPagination) {
                existingPagination.remove();
            }
            container.appendChild(paginationContainer);
        }
    }

    // 切换标签页
    showTab(tabName) {
        this.currentTab = tabName;
        this.currentPage = 1;
        
        // 更新按钮状态
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');

        // 更新内容显示
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-articles`).classList.add('active');

        // 加载对应状态的文章
        let status = null;
        if (tabName === 'drafts') status = 'draft';
        if (tabName === 'trash') status = 'deleted';
        
        this.loadArticles(status);
    }

    // 跳转到指定页面
    async goToPage(page) {
        this.currentPage = page;
        await this.loadArticles(this.getCurrentStatus());
    }

    // 获取当前状态
    getCurrentStatus() {
        switch (this.currentTab) {
            case 'drafts': return 'draft';
            case 'trash': return 'deleted';
            default: return null;
        }
    }

    // 编辑文章
    editArticle(id) {
        window.location.href = `editor.html?id=${id}`;
    }

    // 删除文章
    async deleteArticle(id) {
        if (confirm('确定要删除这篇文章吗？')) {
            try {
                const response = await fetch(`${this.baseUrl}/api/articles/${id}`, {
                    method: 'DELETE'
                });

                const result = await response.json();
                if (result.success) {
                    this.showNotification('文章删除成功', 'success');
                    await this.loadArticles(this.getCurrentStatus());
                } else {
                    this.showNotification('删除失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('删除文章失败:', error);
                this.showNotification('网络错误，删除失败', 'error');
            }
        }
    }

    // 发布文章
    async publishArticle(id) {
        try {
            const response = await fetch(`${this.baseUrl}/api/articles/${id}/publish`, {
                method: 'PUT'
            });

            const result = await response.json();
            if (result.success) {
                this.showNotification('文章发布成功', 'success');
                await this.loadArticles(this.getCurrentStatus());
            } else {
                this.showNotification('发布失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('发布文章失败:', error);
            this.showNotification('网络错误，发布失败', 'error');
        }
    }

    // 恢复文章
    async restoreArticle(id) {
        try {
            const response = await fetch(`${this.baseUrl}/api/articles/${id}/restore`, {
                method: 'PUT'
            });

            const result = await response.json();
            if (result.success) {
                this.showNotification('文章恢复成功', 'success');
                await this.loadArticles(this.getCurrentStatus());
            } else {
                this.showNotification('恢复失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('恢复文章失败:', error);
            this.showNotification('网络错误，恢复失败', 'error');
        }
    }

    // 永久删除
    async permanentDelete(id) {
        if (confirm('确定要永久删除这篇文章吗？此操作不可恢复！')) {
            try {
                const response = await fetch(`${this.baseUrl}/api/articles/${id}/permanent`, {
                    method: 'DELETE'
                });

                const result = await response.json();
                if (result.success) {
                    this.showNotification('文章永久删除成功', 'success');
                    await this.loadArticles(this.getCurrentStatus());
                } else {
                    this.showNotification('永久删除失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('永久删除文章失败:', error);
                this.showNotification('网络错误，删除失败', 'error');
            }
        }
    }

    // 搜索文章
    async searchArticles(query) {
        if (!query.trim()) {
            await this.loadArticles(this.getCurrentStatus());
            return;
        }

        try {
            const response = await fetch(`${this.baseUrl}/api/articles/search?q=${encodeURIComponent(query)}`);
            const result = await response.json();
            
            if (result.success) {
                this.articles = result.data.articles || [];
                this.renderArticles();
                this.renderPagination(result.data.total || 0);
            } else {
                this.showNotification('搜索失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('搜索文章失败:', error);
            this.showNotification('搜索失败，请检查网络连接', 'error');
        }
    }

    // 显示空状态
    renderEmptyState() {
        const containers = document.querySelectorAll('.article-list');
        containers.forEach(container => {
            container.innerHTML = `
                <div style="text-align: center; padding: 60px 20px; color: #666;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; margin-bottom: 20px;"></i>
                    <h3>无法连接到服务器</h3>
                    <p>请检查后端服务是否正常运行</p>
                </div>
            `;
        });
    }

    // 工具函数：获取摘要
    getExcerpt(content, length = 100) {
        // 移除HTML标签
        const text = content.replace(/<[^>]*>/g, '');
        return text.length > length ? text.substring(0, length) + '...' : text;
    }

    // 工具函数：转义HTML
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 工具函数：格式化时间
    formatTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    // 显示通知
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 4px;
            color: white;
            z-index: 1000;
            font-size: 14px;
            background: ${type === 'success' ? '#28a745' : type === 'error' ? '#dc3545' : '#007bff'};
        `;
        notification.textContent = message;
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
}

// 全局函数
function showTab(tabName) {
    blogManager.showTab(tabName);
}

function editArticle(id) {
    blogManager.editArticle(id);
}

function deleteArticle(id) {
    blogManager.deleteArticle(id);
}

function publishDraft(id) {
    blogManager.publishArticle(id);
}

function restoreArticle(id) {
    blogManager.restoreArticle(id);
}

function permanentDelete(id) {
    blogManager.permanentDelete(id);
}

// 初始化博客管理器
let blogManager;

document.addEventListener('DOMContentLoaded', function() {
    blogManager = new BlogManager();
});